﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.IO;
using BartonExtension;
using System.Web;
using Polenter.Serialization;

namespace ZKCache
{
    public class CacheCore
    {
        private string _cachePath;
        private CacheIndex cacheIndex;

        static CacheCore instance;
        public CacheCore(string cachePath)
        {
            _cachePath = cachePath;
            cacheIndex = new CacheIndex();
            cacheIndex.LoadFromDisk(cachePath);
        }

        public T cacheWithIdentifier<T>(string identifier)
        {
            CacheDictionary cache = cacheIndex.cacheDictionaryWithIdentifier(identifier);
            if (cache != null && !cache.IsExpired)
                return cache.objectFromCache<T>();
            else return default(T);
        }
        public void CreateCacheWithIdentifier(string identifier,object willCacheObject,int expireTimespan)
        {
            try
            {
                CacheDictionary cache = new CacheDictionary()
                {
                    cache_create_time = DateTime.Now.ToString(),
                    expired_time = expireTimespan,
                    identifier = identifier,
                    cachePath = _cachePath
                };
                cacheIndex.CreateCache(cache, willCacheObject, _cachePath);
            }
            catch (Exception ex) { }
        }
        public void CreateCacheWithIdentifier(string identifier,object willCacheObject)
        {
            CreateCacheWithIdentifier(identifier, willCacheObject, 15);
        }

        public void refresh()
        {
            cacheIndex.cleanPool();
        }

        public static CacheCore standardCache
        {
            get
            {
                if (instance == null)
                {
                    string path = HttpContext.Current.Server.MapPath("../cache/");
                    if (!Directory.Exists(path))
                        Directory.CreateDirectory(path);
                    instance = new CacheCore(path);
                    instance._cachePath = path;
                }
                return instance;
            }
        }
    }
}
